package com.lmabbe.common.datasources.handle;

import com.lmabbe.common.datasources.mapper.InitRoleMapper;
import com.lmabbe.common.datasources.mapper.InitRoleResourceMapper;
import com.lmabbe.common.datasources.mapper.InitUserMapper;
import com.lmabbe.common.global.context.TenantBuildContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.util.stream.Collectors;

/**
 * 初始化租户基础数据处理器
 *
 * @author lmabbe
 */
@Slf4j
public class InitTenantBaseDataHandle extends InitApplicationHandle {

    public InitTenantBaseDataHandle(ApplicationContext applicationContext, TenantBuildContext tenantContext) {
        super(applicationContext, tenantContext);
    }

    @Override
    void handle(InitApplicationContext context) {
        log.info(">>>>>>>>>初始化租户管理员数据>>>>>>>");
        InitUserMapper initUserMapper = applicationContext.getBean(InitUserMapper.class);

        initUserMapper.initUser(tenantContext.findParamByKey("sys.admin.username"),
                tenantContext.findParamByKey("sys.admin.password"),
                tenantContext.findParamByKey("sys.default.head"));

        log.info(">>>>>>>>>初始化租户管理员数据>>>>>>>");
        InitRoleMapper initRoleMapper = applicationContext.getBean(InitRoleMapper.class);
        initRoleMapper.initRole();

        log.info(">>>>>>>>>初始化租户管理员数据>>>>>>>");
        InitRoleResourceMapper roleResourceMapper = applicationContext.getBean(InitRoleResourceMapper.class);
        roleResourceMapper.initRoleResource(
                tenantContext.getResources().stream()
                        .map(s -> s.getResourceId())
                        .collect(Collectors.toList()));
    }
}
